<script setup>
import {ref, onMounted} from "vue";
import {imageVerifyCodeGetAPI, loginByUsernameOrEmailWithPasswordAPI, loginByEmailWithVerityCodeAPI, emailVerifyCodeGetAPI} from "@/api/FrontApi/user.js";
import 'element-plus/theme-chalk/el-message.css'
import {ElMessage} from "element-plus";
import {useUserStore} from "@/stores/index.js";
import {useRouter} from "vue-router";

const verityCodeImage = ref()

// 获取图形验证码
const getVerityCodeImage = async () => {
  const res = await imageVerifyCodeGetAPI();
  if (res.code === 1) {
    verityCodeImage.value = res.data.image
    loginByPasswordFormData.value.token = res.data.token
  }
}

// 发送邮箱验证码
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
const sendEmailVerityCode = async () => {
  // 检查邮箱是否存在且格式正确
  if (!loginByEmailFormData.value.email) {
    ElMessage.error("请输入邮箱地址");
    return;
  }
  if (!emailRegex.test(loginByEmailFormData.value.email)) {
    ElMessage.error("请输入有效的邮箱地址");
    return;
  }
  const res = await emailVerifyCodeGetAPI(loginByEmailFormData.value.email)
  if (res.code === 1) {
    ElMessage.success("已发送验证码，请注意查收")
  }
}

onMounted(() => getVerityCodeImage())
const loginType = ref(false)

// 切换登录方式
const changeLoginType = () => {
  loginType.value = !loginType.value
}

// 获取图片验证码
// 按钮状态
const isButtonDisabled = ref(false);
const buttonTitle = ref('点击切换图片')
// 设置按钮禁用状态
const setButtonDisabled = () => {
  isButtonDisabled.value = true;
  buttonTitle.value = '请稍等...'
  setTimeout(() => {
    isButtonDisabled.value = false;
    buttonTitle.value = '点击切换图片'
  }, 1000); // 1秒钟
};
const changeVerityCodeImage = () => {
  if (!isButtonDisabled.value) {
    getVerityCodeImage();
    setButtonDisabled();
  }
}

// 是否在电脑上记住我
const rememberMe = ref(false)

// 密码登录表单内容
const loginByPasswordFormData = ref({
  usernameOrEmail: null,
  password: null,
  code: null,
  token: null
})

// 表单校验函数
const validateForm = () => {
  let valid = true
  if (!loginByPasswordFormData.value.usernameOrEmail) {
    ElMessage.warning('请输入用户名或者邮箱')
    valid = false
    return valid
  }
  if (!loginByPasswordFormData.value.password) {
    ElMessage.warning('请输入密码')
    valid = false
    return valid
  }
  if (!loginByPasswordFormData.value.code) {
    ElMessage.warning('请输入验证码')
    valid = false
    return valid
  }
  return valid
}

// 密码登录
const router = useRouter()
const userStore = useUserStore()
const handlePasswordSubmit = async () => {
  if (!validateForm()) {
    return
  }
  const res = await loginByUsernameOrEmailWithPasswordAPI(loginByPasswordFormData.value)
  if (res.code === 1) {
    if (rememberMe.value === true) {
      userStore.token = res.data.token
      userStore.user = res.data.user
    }
    router.push('/')
  }
}

// 忘记密码
const forgetPassword = () => {
  router.push('/fgtpwd')
}

// 邮箱登录表单内容
const loginByEmailFormData = ref({
  email: null,
  code: null
})

// 表单校验函数
const validateEmailForm = () => {
  let valid = true
  if (!loginByEmailFormData.value.email) {
    ElMessage.warning('请输入用户名或者邮箱')
    valid = false
    return valid
  }
  if (!loginByEmailFormData.value.code) {
    ElMessage.warning('请输入验证码')
    valid = false
    return valid
  }
  return valid
}

// 邮箱登录
const handleEmailSubmit = async () => {
  if (!validateEmailForm()) {
    return
  }
  const res = await loginByEmailWithVerityCodeAPI(loginByEmailFormData.value)
  if (res.code === 1) {
    if (rememberMe.value === true) {
      userStore.token = res.data.token
      userStore.user = res.data.user
    }
    router.push('/')
  }
}

// 去注册
const goRegister = () => {
  router.push('/register')
}
</script>

<template>
  <div class="login-page">
    <div class="container">
      <div class="login-content">
        <div class="login">
          <div class="card">
            <h1 class="title">登录</h1>
            <div class="form-card">
              <div class="login-type">
                <span v-if="loginType">邮箱验证码登录</span>
                <span v-if="!loginType">用户名密码登录</span>
                或者使用
                <span @click="changeLoginType" v-if="!loginType">邮箱验证码登录</span>
                <span @click="changeLoginType" v-if="loginType">用户名密码登录</span>
              </div>
              <div v-show="!loginType" class="login-by-password-form">
                <form @submit.prevent="handlePasswordSubmit">
                  <div class="userNameOrEmail">
                    <div class="desc">用户名或者邮箱</div>
                    <input v-model="loginByPasswordFormData.usernameOrEmail" class="userNameOrEmailInput">
                  </div>
                  <div class="password">
                    <div class="desc">
                      <span>密码</span>
                      <span @click="forgetPassword" class="forget-password">忘记密码</span>
                    </div>
                    <input v-model="loginByPasswordFormData.password" type="password" class="passwordInput">
                  </div>
                  <div class="verityCode">
                    <div class="desc">验证码</div>
                    <div class="verity-code-container">
                      <input v-model="loginByPasswordFormData.code" class="verity-code-input">
                      <img @click="changeVerityCodeImage" :src="verityCodeImage" :title="buttonTitle">
                    </div>
                  </div>
                  <div class="remember-me">
                    <el-checkbox v-model="rememberMe">记住我</el-checkbox>
                  </div>
                  <div class="login-submit">
                    <div class="desc"></div>
                    <button type="submit" class="login-submit-button">登录</button>
                  </div>
                </form>
              </div>
              <div v-show="loginType" class="login-by-verity-code-form">
                <form @submit.prevent="handleEmailSubmit">
                  <div class="email">
                    <div class="desc">邮箱</div>
                    <input v-model="loginByEmailFormData.email" class="emailInput">
                  </div>
                  <div class="verity-code">
                    <div class="desc">验证码</div>
                    <div class="verity-code-container">
                      <input v-model="loginByEmailFormData.code" type="password" class="verity-code-input">
                      <div class="send-email-code" @click="sendEmailVerityCode">发送邮箱验证码</div>
                    </div>
                  </div>
                  <div class="remember-me">
                    <el-checkbox v-model="rememberMe">记住我</el-checkbox>
                  </div>
                  <div class="login-submit">
                    <div class="desc"></div>
                    <button type="submit" class="login-submit-button">登录</button>
                  </div>
                </form>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="register-content">
        <div class="go-register">
          <span>没有账户？</span>
          <span @click="goRegister">去注册</span>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped lang="scss">
.login-page {
  .container {
    width: 100%;
    .login-content {
      height: 820px;
      background: radial-gradient(rgba(24, 26, 33, 0) 0%, #181A21 100%) fixed no-repeat, url(/src/assets/images/LoginBGC.jpg) center top no-repeat, #181A21;
      .login {
        padding-top: 80px;
        padding-bottom: 150px;
        display: flex;
        flex-direction: column;
        align-items: center;
        .card {
          display: flex;
          flex-direction: column;
          justify-content: space-between;
          gap: 32px;
          .title {
            color: #fff;
            display: flex;
            flex-direction: column;
            margin: 8px 16px;
          }
          .form-card {
            min-width: 400px;
            min-height: 300px;
            background-color: #181a21;
            border-radius: 4px;
            padding: 24px 96px;
            .login-type {
              color: #384959;
              margin-bottom: 16px;
              span:first-child {
                color: #1999ff;
                font-size: 18px;
              }
              span:nth-child(2) {
                font-size: 14px;
                cursor: pointer;
                &:hover {
                  color: $themeColor;
                }
              }
            }
            .login-by-password-form {
              color: #afafaf;
              font-size: 12px;
              width: 400px;
              .userNameOrEmail {
                margin-bottom: 10px;
                .userNameOrEmailInput {
                  margin-top: 2px;
                  padding: 10px;
                  width: 400px;
                  height: 40px;
                  outline: none;
                  font-size: 15px;
                }
              }
              .password {
                margin-bottom: 10px;
                .desc {
                  display: flex;
                  justify-content: space-between;
                  .forget-password {
                    cursor: pointer;
                    &:hover {
                      color: $themeColor;
                    }
                  }
                }
                .passwordInput {
                  margin-top: 2px;
                  padding: 10px;
                  width: 400px;
                  height: 40px;
                  outline: none;
                  font-size: 15px;
                }
              }
              .verityCode {
                margin-bottom: 10px;
                .verity-code-container {
                  display: flex;
                  justify-content: space-between;
                  .verity-code-input {
                    margin-top: 2px;
                    padding: 10px;
                    width: 180px;
                    height: 40px;
                    outline: none;
                    font-size: 15px;
                  }
                  img {
                    cursor: pointer;
                    margin-top: 2px;
                    height: 40px;
                    width: 140px;
                  }
                }
              }
              .remember-me {
                margin-bottom: 10px;
              }
              .login-submit {
                margin-bottom: 10px;
                display: flex;
                flex-direction: column;
                align-items: center;
                .login-submit-button {
                  width: 270px;
                  background: linear-gradient(90deg, #06BFFF 0%, #2D73FF 100%);
                  border-radius: 2px;
                  border: none;
                  outline: none;
                  padding: 12px;
                  color: #fff;
                  font-size: 16px;
                  font-weight: 400;
                  text-align: center;
                  cursor: pointer;
                }
              }
            }
            .login-by-verity-code-form {
              color: #afafaf;
              font-size: 12px;
              width: 400px;
              .email {
                margin-bottom: 10px;
                .emailInput {
                  margin-top: 2px;
                  padding: 10px;
                  width: 400px;
                  height: 40px;
                  outline: none;
                  font-size: 15px;
                }
              }
              .verity-code {
                margin-bottom: 10px;
                .verity-code-container {
                  display: flex;
                  justify-content: space-between;
                  .verity-code-input {
                    margin-top: 2px;
                    padding: 10px;
                    width: 180px;
                    height: 40px;
                    outline: none;
                    font-size: 15px;
                  }
                  .send-email-code {
                    margin-top: 2px;
                    width: 160px;
                    height: 40px;
                    line-height: 40px;
                    text-align: center;
                    background: linear-gradient(90deg, #ffa4f6 0%, $secondaryColor 100%);
                    border-radius: 2px;
                    color: #fff;
                    font-size: 14px;
                    cursor: pointer;
                    &:hover {
                      background: linear-gradient(90deg, $secondaryColor 0%, #ff2bc0 100%);
                    }
                  }
                }
              }
              .login-submit {
                margin-bottom: 10px;
                display: flex;
                flex-direction: column;
                align-items: center;
                .login-submit-button {
                  width: 270px;
                  background: linear-gradient(90deg, #06BFFF 0%, #2D73FF 100%);
                  border-radius: 2px;
                  border: none;
                  outline: none;
                  padding: 12px;
                  color: #fff;
                  font-size: 16px;
                  font-weight: 400;
                  text-align: center;
                  cursor: pointer;
                }
              }
            }
          }
        }
      }
    }
    .register-content {
      height: 100px;
      display: flex;
      flex-direction: column;
      align-items: center;
      .go-register {
        margin-top: 20px;
        text-align: center;
        span:first-child {
          font-size: 18px;
          color: #dcdedf;
        }
        span:last-child {
          cursor: pointer;
          font-size: 30px;
          color: #1999ff;
          &:hover {
            color: $themeColor;
            border-bottom: 3px solid $themeColor;
          }
        }
      }
    }
  }
}
</style>
